package com.fh.controller.system.user;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.RecordService;
import com.fh.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.Role;
import com.fh.service.system.menu.MenuService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.user.UserService;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * 类名称：UserController
 * 创建人：FH
 * 创建时间：2014年6月28日
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "roleService")
    private RoleService roleService;
    @Resource(name = "menuService")
    private MenuService menuService;
    @Resource(name = "attachmentService")
    private AttachmentService attachmentService;
    @Resource(name = "recordService")
    private RecordService recordService;

    /**
     * 获取所有用户，为了 ztree
     */
    @RequestMapping(value = "/listForZtree")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "room详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        List<PageData> returnList = new ArrayList<>();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> list = userService.listForZtree(pd);
            for (PageData temp : list) {
                PageData single = new PageData();
                single.put("id", temp.get("USER_ID"));
                single.put("name", temp.get("NAME"));
                single.put("pId", "-1");
                returnList.add(single);
            }

            res.put("data", returnList);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 新增账户
     *
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {

        logBefore(logger, "新增用户");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {

            PageData pd1 = new PageData();
            pd1.put("USERNAME", user.getUSERNAME());
            PageData uPd = userService.findByUId(pd1);

            pd.put("USER_ID", this.get32UUID());    //ID
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
            pd.put("RIGHTS", "1133671055321055258374707980945218933803269864762743594642571294"); //
            pd.put("ROLE_ID", "1"); //默认权限
            pd.put("LAST_LOGIN", new DateUtil().getTime()); //最后登录时间
            pd.put("IP", "0:0:0:0:0:0:0:1"); //IP
            pd.put("STATUS", "0"); //状态
            pd.put("SKIN", "default"); //默认皮肤
            pd.put("CREATE_ID", user.getUSER_ID()); //创建者ID
            pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            pd.put("IS_DEL", "0"); //已删除
            pd.put("USER_TYPE", "63d5ecdb7af94593866a36eb026daaa6"); //账户类型
            pd.put("COMPANY_ID", uPd.get("COMPANY_ID")); //公司ID
            if (null == userService.findByUIdSave(pd)) {
                userService.saveU(pd);
                res.put("data", "");
                res.put("errcode", "0");
                res.put("errmsg", "ok");

                //保存全局记录
                PageData SystemPd = new PageData();
                SystemPd.put("ID", this.get32UUID());//主键
                SystemPd.put("IS_DEL", 0); //是否删除
                SystemPd.put("SORT", 0); //排序
                SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                SystemPd.put("DETAILS","新增用户");
                SystemPd.put("OPERA_TIME",new DateUtil().getTime());
                SystemPd.put("OPERATOR",user.getNAME());
                SystemPd.put("IP",user.getIP());
                SystemPd.put("OP_PD",pd.toString());
                recordService.SaveSystem(SystemPd);
            } else {
                res.put("data", "");
                res.put("errcode", "1");
                res.put("errmsg", "the account already exists");
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    @RequestMapping(value = "/saveU")
    public ModelAndView saveU(PrintWriter out) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        pd.put("USER_ID", this.get32UUID());    //ID
        pd.put("RIGHTS", "");                    //权限
        pd.put("LAST_LOGIN", "");                //最后登录时间
        pd.put("IP", "");                        //IP
        pd.put("STATUS", "0");                    //状态
        pd.put("SKIN", "default");                //默认皮肤

        pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());

        if (null == userService.findByUId(pd)) {
            userService.saveU(pd);
            mv.addObject("msg", "success");
        } else {
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 判断用户名是否存在
     */
    @RequestMapping(value = "/hasU")
    public void hasU(PrintWriter out) {
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            if (userService.findByUId(pd) != null) {
                out.write("error");
            } else {
                out.write("success");
            }
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 判断邮箱是否存在
     */
    @RequestMapping(value = "/hasE")
    public void hasE(PrintWriter out) {
        PageData pd = new PageData();
        try {
            pd = this.getPageData();

            if (userService.findByUE(pd) != null) {
                out.write("error");
            } else {
                out.write("success");
            }
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 判断编码是否存在
     */
    @RequestMapping(value = "/hasN")
    public void hasN(PrintWriter out) {
        PageData pd = new PageData();
        try {
            pd = this.getPageData();

            if (userService.findByUN(pd) != null) {
                out.write("error");
            } else {
                out.write("success");
            }
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 修改用户
     */
    @RequestMapping(value = "/editU")
    public ModelAndView editU(PrintWriter out) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))) {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
        }
        userService.editU(pd);
        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }


    /**
     * 去修改用户页面
     */

    @RequestMapping(value = "/goEditU")
    public ModelAndView goEditU() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        //顶部修改个人资料
        String fx = pd.getString("fx");


        if ("head".equals(fx)) {
            mv.addObject("fx", "head");
        } else {
            mv.addObject("fx", "user");
        }

        List<Role> roleList = roleService.listAllERRoles();            //列出所有二级角色
        pd = userService.findByUiId(pd);                            //根据ID读取
        mv.setViewName("system/user/user_edit");
        mv.addObject("msg", "editU");
        mv.addObject("pd", pd);
        mv.addObject("roleList", roleList);

        return mv;
    }

    /**
     * 去新增用户页面
     */
    @RequestMapping(value = "/goAddU")
    public ModelAndView goAddU() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        List<Role> roleList;

        roleList = roleService.listAllERRoles();            //列出所有二级角色

        mv.setViewName("system/user/user_edit");
        mv.addObject("msg", "saveU");
        mv.addObject("pd", pd);
        mv.addObject("roleList", roleList);

        return mv;
    }

    /**
     * 返回json
     */
    @RequestMapping(value = "/json")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = userService.listPdPageUser(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 通过ID获取账户详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() {
        logBefore(logger, "详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData data = userService.findByUserId(pd);

            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 通过ID获取账户详情信息
     */
    @RequestMapping(value = "/findone")
    @ResponseBody
    public PageData findone() {
        logBefore(logger, "findone");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("USER_ID", user.getUSER_ID());
            PageData data = userService.findByUserIdone(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 修改当前用户信息（用户管理）
     */
    @RequestMapping(value = "/edituser")
    @ResponseBody
    public PageData edituser() {
        logBefore(logger, "修改用户");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd.put("USER_ID", user.getUSER_ID());
            if (pd.getString("PASSWORD") != null && !pd.getString("PASSWORD").equals("")) {
                pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
            }
            PageData imgPd = new PageData();
            if(pd.containsKey("ATTACHMENT[name]")){
                String name = pd.get("ATTACHMENT[name]").toString();
                imgPd.put("NAME", name);
            }
            if(pd.containsKey("ATTACHMENT[size]")){
                String size = pd.get("ATTACHMENT[size]").toString();
                imgPd.put("SIZE", size);
            }
            if(pd.containsKey("ATTACHMENT[ext]")){
                String ext = pd.get("ATTACHMENT[ext]").toString();
                imgPd.put("EXT", ext);
            }
            if(pd.containsKey("ATTACHMENT[url]")){
                String url = pd.get("ATTACHMENT[url]").toString();
                imgPd.put("PATH", url);

            }
            imgPd.put("ID", this.get32UUID());
            imgPd.put("OID", user.getUSER_ID());
            imgPd.put("SORT", 1);
            imgPd.put("TYPE", "photo");
            imgPd.put("REMARK", "");
            imgPd.put("CREATE_TIME", new DateUtil().getTime());
            imgPd.put("CREATE_ID", user.getUSER_ID());
            imgPd.put("IS_DELETED", 0);
            // 删除头像
            attachmentService.realDeleteAttachmentByOid(imgPd);

            // 新增头像
            attachmentService.saveAttachment(imgPd);

            userService.edituser(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改当前用户信息");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 修改当前用户信息（用户管理）
     */
    @RequestMapping(value = "/dele")
    @ResponseBody
    public PageData dele() {
        logBefore(logger, "修改用户");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {

            userService.dele(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改用户");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 修改当前用户信息（账户设置）
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "修改User");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            if(pd.containsKey("IS_DEL")){
            }else {
                if(!"".equals((pd.getString("PASSWORD")).toString())){
                    pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
                }
            }
            userService.edit(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改用户");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 显示用户列表(用户组)
     */
    @RequestMapping(value = "/listUsers")
    public ModelAndView listUsers(Page page) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();

        String USERNAME = pd.getString("USERNAME");

        if (null != USERNAME && !"".equals(USERNAME)) {
            USERNAME = USERNAME.trim();
            pd.put("USERNAME", USERNAME);
        }

        String lastLoginStart = pd.getString("lastLoginStart");
        String lastLoginEnd = pd.getString("lastLoginEnd");

        if (lastLoginStart != null && !"".equals(lastLoginStart)) {
            lastLoginStart = lastLoginStart + " 00:00:00";
            pd.put("lastLoginStart", lastLoginStart);
        }
        if (lastLoginEnd != null && !"".equals(lastLoginEnd)) {
            lastLoginEnd = lastLoginEnd + " 00:00:00";
            pd.put("lastLoginEnd", lastLoginEnd);
        }

        page.setPd(pd);
        List<PageData> userList = userService.listPdPageUser(page);            //列出用户列表
        List<Role> roleList = roleService.listAllERRoles();                        //列出所有二级角色

        mv.setViewName("system/user/user_list");
        mv.addObject("userList", userList);
        mv.addObject("roleList", roleList);
        mv.addObject("pd", pd);
        mv.addObject(Const.SESSION_QX, this.getHC());    //按钮权限
        return mv;
    }

    /**
     * 显示用户列表(tab方式)
     */
    @RequestMapping(value = "/listtabUsers")
    public ModelAndView listtabUsers(Page page) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        List<PageData> userList = userService.listAllUser(pd);            //列出用户列表
        mv.setViewName("system/user/user_tb_list");
        mv.addObject("userList", userList);
        mv.addObject("pd", pd);
        mv.addObject(Const.SESSION_QX, this.getHC());    //按钮权限
        return mv;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/deleteU")
    public void deleteU(PrintWriter out) {
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            userService.deleteU(pd);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public Object register() {
        logBefore(logger, "注册");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            String code = pd.getString("code");
            String sessionCode = String.valueOf(this.getHttpSession().getAttribute(Const.SESSION_SECURITY_CODE));
            if (StringHelper.isNotEmpty(code) && code.equals(sessionCode)) {
                String id = this.get32UUID();
                pd.put("id", id);
                pd.put("createDate", DateUtil.getTime());
                pd.put("createId", id);
                pd.put("isDel", 0);
                pd.put("companyId", this.get32UUID());
                pd.put("userName", pd.getString("phone"));
                pd.put("password", new SimpleHash("SHA-1", pd.getString("phone"), pd.getString("password")).toString());
                userService.register(pd);
                resultPd.put("data", pd);
                resultPd.put("errcode", "00");
                resultPd.put("errmsg", "注册成功");
            } else {
                resultPd.put("data", pd);
                resultPd.put("errcode", "01");
                resultPd.put("errmsg", "验证码错误");
            }

        } catch (Exception e) {
            resultPd.put("errcode", "02");
            resultPd.put("errmsg", "注册失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/forgetPassword")
    @ResponseBody
    public Object forgetPassword() {
        logBefore(logger, "找回密码");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            String code = pd.getString("code");
            String sessionCode = String.valueOf(this.getHttpSession().getAttribute(Const.SESSION_SECURITY_CODE));
            if (StringHelper.isNotEmpty(code) && code.equals(sessionCode)) {
                pd.put("password", new SimpleHash("SHA-1", pd.getString("phone"), pd.getString("password")).toString());
                userService.forgetPassword(pd);
                resultPd.put("data", pd);
                resultPd.put("errcode", "00");
                resultPd.put("errmsg", "密码找回成功");
            } else {
                resultPd.put("data", pd);
                resultPd.put("errcode", "01");
                resultPd.put("errmsg", "验证码错误");
            }

        } catch (Exception e) {
            resultPd.put("errcode", "02");
            resultPd.put("errmsg", "找回失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/sendsms")
    @ResponseBody
    public Object sendSms() {
        logBefore(logger, "发送验证码");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            int code = Tools.getRandomNum();
            String msg = "【守护神】您好，您的验证码是:" + code + "，请注意查收。";
            sendSMS(pd.getString("phone"), msg);
            this.getHttpSession().setAttribute(Const.SESSION_SECURITY_CODE, code);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "发送成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "发送失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    public void sendSMS(String mobile, String msg) {
        String uid = "15040598011";
        String pwd = MD5.md5("leo123456");
        String dtime = DateUtil.getTime();
        String linkid = UuidUtil.get32UUID();
        SmsUtil.sms3(uid, pwd, mobile, msg, dtime, linkid);
    }


    @RequestMapping(value = "/findbyusername")
    @ResponseBody
    public Object findByUserName() {
        logBefore(logger, "通过用户名查用户是否可使用");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            pd = userService.findByUserName(pd);
            if (pd == null) {
                resultPd.put("errcode", "00");
                resultPd.put("errmsg", "账号可安全使用");
            } else {
                resultPd.put("errcode", "01");
                resultPd.put("errmsg", "该账号已注册，请联系管理员使用");
            }
        } catch (Exception e) {
            resultPd.put("errcode", "02");
            resultPd.put("errmsg", "查询失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAllU")
    @ResponseBody
    public Object deleteAllU() {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String USER_IDS = pd.getString("USER_IDS");

            if (null != USER_IDS && !"".equals(USER_IDS)) {
                String ArrayUSER_IDS[] = USER_IDS.split(",");
                userService.deleteAllU(ArrayUSER_IDS);
                pd.put("msg", "ok");
            } else {
                pd.put("msg", "no");
            }

            pdList.add(pd);
            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }
    //===================================================================================================

    //个人资料接口APP

    /**
     * 通过ID获取账户详情信息
     */
    @RequestMapping(value = "/personal")
    @ResponseBody
    public PageData personal() {
        logBefore(logger, "personal");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        PageData pds = this.getPageData();
        List<PageData> attachmentData=null;
        PageData data =null;
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            if (pd.size() == 0) {
                res.put("data", " ");
            } else {
                data = userService.findByUiId(pd);
                pds.put("id", data.get("USER_ID"));
                attachmentData = attachmentService.findByOId(pds);/* 查看附件 */
                if (attachmentData.size() == 0) {
                    data.put("HEAD", "");
                } else {
                    data.put("HEAD", attachmentData.get(0).get("PATH"));
                }
                res.put("data", data);
            }
            res.put("errcode", "0");
            res.put("errmsg", "ok");

        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * APP修改当前用户密码
     */
    @RequestMapping(value = "/editpassword")
    @ResponseBody
    public PageData editpassword() {
        logBefore(logger, "修改用户密码");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd.put("USER_ID", pd.get("userid"));
            pd.put("PASSWORD", pd.get("password"));
            if (pd.getString("password") != null && !pd.getString("password").equals("")) {
                pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("userName"), pd.getString("password")).toString());
            }
            userService.edituser(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", pd.get("userid")); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","手机端修改当前用户密码");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",pd.get("userName"));
            SystemPd.put("IP","");
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }
    //===================================================微信公众号用户管理================================================
    /**
     * 返回全微信公众号管理 是否授权绑定指定合同
     */
    @RequestMapping(value = "/weixin_user")
    @ResponseBody
    public Object weixin_user(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            pd = this.getPageData();
            getPData(page, pd);
            varList = userService.findWeixinUser(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 公众号关联处理ajax
     */
    @RequestMapping(value = "/weixin_open")
    @ResponseBody
    public PageData weixin_open() {
        logBefore(logger, "公众号关联处理ajax");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            userService.weixin_open(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    //===================================================================================================
    /*
	 * 导出用户信息到EXCEL
	 * @return
	 */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel() {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {

            //检索条件===
            String USERNAME = pd.getString("USERNAME");
            if (null != USERNAME && !"".equals(USERNAME)) {
                USERNAME = USERNAME.trim();
                pd.put("USERNAME", USERNAME);
            }
            String lastLoginStart = pd.getString("lastLoginStart");
            String lastLoginEnd = pd.getString("lastLoginEnd");
            if (lastLoginStart != null && !"".equals(lastLoginStart)) {
                lastLoginStart = lastLoginStart + " 00:00:00";
                pd.put("lastLoginStart", lastLoginStart);
            }
            if (lastLoginEnd != null && !"".equals(lastLoginEnd)) {
                lastLoginEnd = lastLoginEnd + " 00:00:00";
                pd.put("lastLoginEnd", lastLoginEnd);
            }
            //检索条件===

            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();

            titles.add("用户名");        //1
            titles.add("编号");        //2
            titles.add("姓名");            //3
            titles.add("职位");            //4
            titles.add("手机");            //5
            titles.add("邮箱");            //6
            titles.add("最近登录");        //7
            titles.add("上次登录IP");    //8

            dataMap.put("titles", titles);

            List<PageData> userList = userService.listAllUser(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < userList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", userList.get(i).getString("USERNAME"));        //1
                vpd.put("var2", userList.get(i).getString("NUMBER"));        //2
                vpd.put("var3", userList.get(i).getString("NAME"));            //3
                vpd.put("var4", userList.get(i).getString("ROLE_NAME"));    //4
                vpd.put("var5", userList.get(i).getString("PHONE"));        //5
                vpd.put("var6", userList.get(i).getString("EMAIL"));        //6
                vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));    //7
                vpd.put("var8", userList.get(i).getString("IP"));            //8
                varList.add(vpd);
            }

            dataMap.put("varList", varList);

            ObjectExcelView erv = new ObjectExcelView();                    //执行excel操作

            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 打开上传EXCEL页面
     */
    @RequestMapping(value = "/goUploadExcel")
    public ModelAndView goUploadExcel() throws Exception {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/user/uploadexcel");
        return mv;
    }

    /**
     * 下载模版
     */
    @RequestMapping(value = "/downExcel")
    public void downExcel(HttpServletResponse response) throws Exception {

        FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");

    }

    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value = "/readExcel")
    public ModelAndView readExcel(
            @RequestParam(value = "excel", required = false) MultipartFile file
    ) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();

        if (null != file && !file.isEmpty()) {
            String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;                                //文件上传路径
            String fileName = FileUpload.fileUp(file, filePath, "userexcel");                            //执行上传

            List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);    //执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			
			/*存入数据库操作======================================*/
            pd.put("RIGHTS", "");                    //权限
            pd.put("LAST_LOGIN", "");                //最后登录时间
            pd.put("IP", "");                        //IP
            pd.put("STATUS", "0");                    //状态
            pd.put("SKIN", "default");                //默认皮肤

            List<Role> roleList = roleService.listAllERRoles();    //列出所有二级角色

            pd.put("ROLE_ID", roleList.get(0).getROLE_ID());    //设置角色ID为随便第一个
            /**
             * var0 :编号
             * var1 :姓名
             * var2 :手机
             * var3 :邮箱
             * var4 :备注
             */
            for (int i = 0; i < listPd.size(); i++) {
                pd.put("USER_ID", this.get32UUID());                                        //ID
                pd.put("NAME", listPd.get(i).getString("var1"));                            //姓名

                //String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"));	//根据姓名汉字生成全拼
                String USERNAME = "";
                pd.put("USERNAME", USERNAME);
                if (userService.findByUId(pd) != null) {                                        //判断用户名是否重复
                    //USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"))+Tools.getRandomNum();
                    pd.put("USERNAME", USERNAME);
                }
                pd.put("BZ", listPd.get(i).getString("var4"));                                //备注
                if (Tools.checkEmail(listPd.get(i).getString("var3"))) {                        //邮箱格式不对就跳过
                    pd.put("EMAIL", listPd.get(i).getString("var3"));
                    if (userService.findByUE(pd) != null) {                                    //邮箱已存在就跳过
                        continue;
                    }
                } else {
                    continue;
                }

                pd.put("NUMBER", listPd.get(i).getString("var0"));                            //编号已存在就跳过
                pd.put("PHONE", listPd.get(i).getString("var2"));                            //手机号

                pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString());    //默认密码123
                if (userService.findByUN(pd) != null) {
                    continue;
                }
                userService.saveU(pd);
            }
			/*存入数据库操作======================================*/

            mv.addObject("msg", "success");
        }

        mv.setViewName("save_result");
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }


    /* ===============================权限================================== */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
	/* ===============================权限================================== */
}
